package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 定时任务类，处理超时未支付订单，和派送中未点已完成的订单
     * 每分钟检查一次待支付的状态的订单，通过校验下单时间，来判断是否超过15分钟，如果超过则将订单状态改为已取消
     * 每晚11点检查一次是否有处于派送中的订单，将状态改为已完成
     */

    @Scheduled(cron = "0 * * * * ? ")  // 每分钟执行一次
    public void handleTimeoutOrder() {
        log.info("处理超时订单,{}", new Date());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //查询orders表中状态为1待付款且下单时间在当前时间-15分钟之前的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);

        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orderItem -> {
                Orders orders = new Orders();
                orders.setId(orderItem.getId());
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());

                orderMapper.update(orders);
            });
        }
    }

    @Scheduled(cron = "0 0 23 * * ?")  // 每天23点执行一次
    public void handleDeliveryOrder() {
        log.info("定时处理派送中订单,{}", new Date());

        LocalDateTime time = LocalDateTime.now();

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.COMPLETED, time);

        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orderItem -> {
                Orders orders = new Orders();
                orders.setId(orderItem.getId());
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());

                orderMapper.update(orders);
            });
        }
    }

}
